<!doctype html>

<html>

  <head>
    <meta charset="utf-8">
    <title>WASM test</title>
  </head>

  <body>
 
<script type="module">
      // allow use of async/await
      (async () => {
        // Build the WebAssembly instance.
        const memory = new WebAssembly.Memory({ initial: 2 });
        const response = await fetch('lenstr.wasm');
        const bytes = await response.arrayBuffer();
        const { instance } = await WebAssembly.instantiate(bytes, {
          env: { memory }
        });

        // Text to copy.
        const text = 'Hello from wasm sfg.c!';

        // Configure shared memory.
        const view = new Uint8Array(memory.buffer);
        const pInput = instance.exports.__heap_base;
        const pOutput = pInput + 1024;

        encode(view, pInput, text);

        // run our own strlen()
        const bytesCopied = instance.exports.lenstr(pInput);

        console.log('text.length is ', text.length);
        console.log('lenstr() length is ', bytesCopied);
        console.log('input string is ', decode(view, pInput));
      })();

      // Encode string into memory starting at address base.
      const encode = (memory, base, string) => {
        for (let i = 0; i < string.length; i++) {
          memory[base + i] = string.charCodeAt(i);
        }

        memory[base + string.length] = 0;
      };

      // Decode a string from memory starting at address base.
      const decode = (memory, base) => {
        let cursor = base;
        let result = '';

        while (memory[cursor] !== 0) {
          result += String.fromCharCode(memory[cursor++]);
        }

        return result;
      };
    </script>
  </body>

</html>


